package initialize

import (
	"serial-port-go/lib/serial"
	"serial-port-go/lib/utils"
	"serial-port-go/src/basic/base"
	"serial-port-go/src/machine/listener"
	"serial-port-go/src/machine/reader"
)

//Run 初始化
func Run() {
	base.Logger.Info().Println(" -- starting init")
	base.Logger.Info().Println(" -- read config.json")
	initJsonConfig()
	loadOptions()
	base.Logger.Info().Println(" -- init serial port")
	initSerialPort()
	base.Logger.Info().Println(" -- init succeed")
}

// initJsonConfig NO.1 initialize
// 初始化JsonConfig
func initJsonConfig() {
	reader.ReadConfigJson()
}

// loadOptions NO.2 转存储options
func loadOptions() {
	options := base.Properties.PortOptions
	for i := range options {
		base.Options = append(base.Options, options[i])
	}
}

//initSerialPort NO.3 initialize
//初始化串口并监听
func initSerialPort() {
	for i := range base.Options {
		openAndStartListen(base.Options[i])
	}
}

func openAndStartListen(options serial.OpenOptions) {
	portRW := utils.OpenSerialPort(options)
	base.SerialPortMap[options.PortName] = portRW
	go listener.Listen(options.PortName)
}
